package crp.core.workflow.domain.listeners;

import com.qwlabs.cdi.Primary;
import crp.core.workflow.domain.events.WorkflowInstanceEnded;
import crp.core.workflow.domain.events.WorkflowInstanceStarted;
import crp.core.workflow.domain.events.WorkflowTaskEnded;
import crp.core.workflow.domain.events.WorkflowTaskStarted;
import crp.core.workflow.domain.services.WorkflowEngine;
import crp.core.workflow.domain.services.WorkflowEventHandler;
import crp.core.workflow.domain.services.WorkflowInstanceSearcher;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;

@ApplicationScoped
public class WorkflowEventListener {
    private final WorkflowEventHandler eventHandler;
    private final WorkflowEngine workflowEngine;
    private final WorkflowInstanceSearcher instanceSearcher;

    @Inject
    public WorkflowEventListener(@Primary WorkflowEventHandler eventHandler,
                                 WorkflowEngine workflowEngine,
                                 WorkflowInstanceSearcher instanceSearcher) {
        this.eventHandler = eventHandler;
        this.workflowEngine = workflowEngine;
        this.instanceSearcher = instanceSearcher;
    }


    public void onEvent(@Observes WorkflowInstanceStarted event) {
        eventHandler.onEvent(event);
        instanceSearcher.byId(event.getInstanceId())
                .ifPresent(workflowEngine::nextTask);
    }

    public void onEvent(@Observes WorkflowInstanceEnded event) {
        eventHandler.onEvent(event);
    }

    public void onEvent(@Observes WorkflowTaskStarted event) {
        eventHandler.onEvent(event);
        if (event.autocomplete()) {
            workflowEngine.autoDoneTask(event.getInstance(), event.getTask());
        }
    }

    public void onEvent(@Observes WorkflowTaskEnded event) {
        eventHandler.onEvent(event);
    }
}
